package com.jmp.autocofiguration.web.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 请求记录，统计处理时间
 *
 * @author cjr
 */
//@WebFilter(urlPatterns = "/*", filterName = "processTimeFilter")
//@Order(1)
@Slf4j
public class ProcessTimeFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("process：{} {} {} {}", request.getMethod(), request.getRequestURI(), request.getHeader(HttpHeaders.CONTENT_TYPE), request.getHeader(HttpHeaders.ACCEPT));
        long stime = System.currentTimeMillis();
        try {
            filterChain.doFilter(request, response);
        } finally {
            long processTime = System.currentTimeMillis() - stime; //ms
            if (processTime > 200) {
                log.warn("process time: {}ms", processTime);
            } else {
                log.debug("process time: {}ms", processTime);
            }
        }
    }
}
